package cn.edu.sdjzu.xg.bysj.controller.basic;

import cn.edu.sdjzu.xg.bysj.domain.Department;
import cn.edu.sdjzu.xg.bysj.service.DepartmentService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import util.Condition;
import util.ControllerHelper;
import util.JSONUtil;
import util.Pagination;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

@WebServlet("/department.ctl")
@Slf4j
public class DepartmentController extends HttpServlet {
    /**
     *
     * 把一个或所有系对象响应到前端
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            respMessage_jsonObj.put("message","未收到请求信息！");
            response.getWriter().println(respMessage_jsonObj);
            log.error("未收到请求消息");
            return;
        }
        //从JSONObject对象中读取键“id”的值（Java Object对象），req_jsonObj可能是{"id":1}
        Object id_obj = req_jsonObj.get("id");
        try {
            //如果id_Obj != null, 说明请求数据有id键，是请求某个教师对象
            if (id_obj != null) {
                int id_int = Integer.parseInt(id_obj.toString());
                responseDepartment(id_int, response);
                log.trace("查找id" + id_int);
            } else {//请求中包含条件和分页信息，需要响应多个教师对象
                //读取分页信息，形成分页对象
                //从JSONObject对象中读取 “pagination” 键对应的值(JSONObject对象)
                Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
                //从请求JSONObject对象中读取键“condition”对应的值(描述查询条件的JSONArray对象)
                List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
                //响应多个教师信息，其中condition, pagination两个对象引用为空是可能的
                this.responseDepartments(response, conditionList, pagination);
            }
        } catch (SQLException e){
            respMessage_jsonObj.put("message","数据库异常");
            log.error("数据库异常"+ e.getMessage());
        } catch(Exception e){
            respMessage_jsonObj.put("message","网络异常");
            log.error("网络异常" + e.getMessage());
        }
        finally {
            response.getWriter().println(respMessage_jsonObj);
        }
    }

    /**
     * 添加
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        //获得请求
        String add_request_json = JSONUtil.getJSON(req);
        JSONObject message = new JSONObject();
        try {
            //解析为待添加的的department对象
            Department department = JSON.parseObject(add_request_json, Department.class);
            //添加进数据库
            DepartmentService.getInstance().add(department);
            message.put("message","添加成功");
        }catch (SQLException e){
            message.put("message","数据库异常");
            //输出错误信息
            log.error("数据库异常" + e.getMessage());
        }catch (Exception e){
            message.put("message","网络异常" + e.getMessage());
            //输出错误信息
            log.error("网络异常");
        }
        resp.getWriter().println(message);
    }

    /**
     * 修改
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        //获得请求
        String update_request_json = JSONUtil.getJSON(req);
        JSONObject message = new JSONObject();
        try {
            //解析为待更新的department对象
            Department department = JSON.parseObject(update_request_json, Department.class);
            //修改进数据库
            DepartmentService.getInstance().update(department);
            message.put("message","更新成功");
        }catch (SQLException e){
            message.put("message","数据库异常");
            log.error("数据库异常" + e.getMessage());
            //输出错误信息
        }catch (Exception e){
            message.put("message","网络异常" + e.getMessage());
            log.error("网络异常");
            //输出错误信息
        }
        resp.getWriter().println(message);
    }

    /**
     * 删除
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //将request参数转换为JSON字串
        String request_json_str = JSONUtil.getJSON(req);
        //将请求body解析为要删除的id对应的JSONObject对象(可能是{"id":1})
        JSONObject idOfTeacherToDelete_jsonObj = JSON.parseObject(request_json_str);
        //从JSONObject对象中读取键“id”的值（Java Object对象），
        Object id_obj = idOfTeacherToDelete_jsonObj.get("id");
        int id_int = Integer.parseInt(id_obj.toString());
        log.trace("删除id" + id_int);
        //设置响应字符编码为UTF-8
        resp.setContentType("application/json;charset=UTF-8");
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //到数据库表中删除对应的教师
            DepartmentService.getInstance().delete(id_int);
            respMessage_jsonObj.put("message", "删除成功");
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            log.error("数据操作异常" + e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            log.error("网络异常" + e.getMessage());
        }
        //响应respMessage_jsonObj到前端
        resp.getWriter().println(respMessage_jsonObj);
    }
    /**
     * 根据请求id查找
     * @param response
     * @param id
     * @throws SQLException
     * @throws IOException
     */
    private void responseDepartment(int id, HttpServletResponse response) throws SQLException, IOException {
        //根据id查找
        Department department = DepartmentService.getInstance().find(id);
        //查找到的department解析为json字串
        String department_json = JSON.toJSONString(department);
        //响应回前端
        response.getWriter().println(department_json);
    }

    /**
     *
     * @param response
     * @param condition
     * @param pagination
     * @throws SQLException
     * @throws IOException
     */
    private void responseDepartments(HttpServletResponse response, Collection<Condition> condition, Pagination pagination) throws SQLException, IOException {
        //按照分页于条件查询对象集合
        Collection<Department> departments = DepartmentService.getInstance().findAll(condition,pagination);
        //解析为json字串
        String department_json = JSON.toJSONString(departments, SerializerFeature.DisableCircularReferenceDetect);
        //新建response_json对象，以便向前台响应消息
        JSONObject response_json = new JSONObject();
        //元组总数
        response_json.put("totalNum",pagination.getTotalNum());
        //查找到的对象集合
        response_json.put("data",department_json);
        //响应回前端
        response.getWriter().println(response_json);
    }

}
